<template>
    <div class="product-selector">
        <!-- 触发按钮 -->
        <div class="trigger-box" :class="size" @click="showDialog" v-if="btnStyle == 1">
            <div class="el-input el-input--suffix">
                <div class="el-input__inner">
                    <template v-if="selectedItems.length > 0">
                        <span class="selected-content">
                            <!-- 多选模式显示标签 -->
                            <template v-if="multiple">
                                <el-tag
                                    v-for="item in selectedItems"
                                    :key="item.id"
                                    closable
                                    size="mini"
                                    @close.stop="removeSelected(item)">
                                    {{ item.name }}
                                </el-tag>
                            </template>
                            <!-- 单选模式显示文字 -->
                            <template v-else>
                                {{ selectedItems[0].name }}
                            </template>
                        </span>
                        <i class="el-select__caret el-input__icon el-icon-circle-close" @click.stop="clearSelection"></i>
                    </template>
                    <template v-else>
                        <span class="placeholder">{{ placeholder }}</span>
                        <i class="el-icon-arrow-down el-input__icon"></i>
                    </template>
                </div>
            </div>
        </div>

        <el-button v-if="btnStyle == 2" type="primary" icon="el-icon-plus" plain  @click="showDialog">选择可回收物</el-button>

        <!-- 选择弹窗 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" :append-to-body="true">
            <div class="dialog-content">
                <!-- 搜索栏 -->
                <el-input v-model="searchKeyword" placeholder="输入可回收物搜索" prefix-icon="el-icon-search" class="search-input" />

                <!-- 最近使用 -->
                <!-- <div v-if="recentItems.length > 0" class="recent-section">
                    <div class="section-header">
                        <div class="section-title">最近使用</div>
                        <el-button type="text" size="mini" @click.stop="clearAllRecent" class="clear-all">
                            清空
                        </el-button>
                    </div>
                    <div class="recent-items">
                        <el-tag v-for="item in recentItems" :key="item.id" class="recent-tag"
                            @click="handleSelect(item)" closable @close.prevent="removeRecentItem(item)">
                            {{ item.name }}
                        </el-tag>
                    </div>
                </div> -->

                <el-row :gutter="20">
                    <!-- 分类树 -->
                    <el-col :span="6" class="category-tree">
                        <div class="section-title">类型</div>
                        <el-tree 
                            ref="categoryTree" 
                            :data="categories" 
                            :props="treeProps" 
                            :load="loadCategories" 
                            :default-expanded-keys="defaultExpandedKeys"
                            lazy
                            node-key="id" 
                            highlight-current 
                            @node-click="handleCategoryClick">
                            <span class="custom-tree-node" slot-scope="{ node, data }">
                                <i class="el-icon-folder-opened"></i>
                                {{ node.label }}
                            </span>
                        </el-tree>
                    </el-col>

                    <!-- 可回收物列表 -->
                    <el-col :span="18" class="product-list">
                        <div class="section-title">选择可回收物</div>
                        <div v-if="filteredProducts.length > 0" class="product-items">
                            <!-- 可回收物列表 -->
                            <div v-for="item in filteredProducts" 
                                :key="item.id" 
                                class="product-item"
                                :class="{ 
                                    'selected': isSelected(item),
                                    'multi-selected': multiple && isSelected(item)
                                }"
                                @click="handleItemClick(item)">
                                <div class="name">{{ item.name }}</div>
                                <!-- <div class="remark">收货价：{{ item.price }}元/KG</div> -->
                                <!-- <div class="remark">{{ item.remarks || '暂无备注' }}</div> -->
                                <!-- <i v-if="isSelected(item)" class="el-icon-check selected-icon"></i> -->
                            </div>
                        </div>
                        <el-empty v-else description="未找到相关可回收物" />
                    </el-col>
                </el-row>
            </div>
            <span slot="footer" class="dialog-footer" v-if="multiple == true">
                <!-- <el-button @click="dialogVisible = false">取消</el-button> -->
                <el-button type="primary" @click="confirmSelect">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    props: {
        value: {
            type: [Number, String, Array],
            default: null
        },
        multiple: { // 多选模式开关
            type: Boolean,
            default: false
        },
        placeholder: {
            type: String,
            default: '请选择可回收物'
        },
        dialogTitle: {
            type: String,
            default: '选择可回收物'
        },
        size:{
            type: String,
            default: 'default'
        },
        btnStyle:{
            type: Number,
            default: 1  //1、输入框样式 2、按钮样式
        },
        dataPERType:{ //数据权限类型:注意dataPERType参数（这是数据权限参数）  如果是收货的时候选类型传dataPERType=2(收货权限),卖货的时候传dataPERType=3(卖货权限)， 后台管理时候传dataPERType=1(收货或卖货权限)
            type: Number,
            default: 1
        }
    },
    data() {
        return {
            dialogVisible: false,
            searchKeyword: '',
            defaultExpandedKeys: [0], // 默认展开全部节点
            categories: [
                // // 添加静态的"全部"节点
                // {
                //     id: 0,
                //     name: '全部',
                //     isLeaf: false,
                //     children: []
                // }
            ],
            products: [],
            selectedItem: null,
            selectedItems: [], // 统一用数组存储
            recentItems: [],
            treeProps: {
                label: 'name',
                children: 'children',
                isLeaf: 'isLeaf'
            }
        }
    },
    computed: {
        filteredProducts() {
            const keyword = this.searchKeyword.toLowerCase()
            return this.products.filter(item =>
                item.name.toLowerCase().includes(keyword) ||
                (item.remarks && item.remarks.toLowerCase().includes(keyword))
            )
        }
    },
    watch: {
        value: {
            immediate: true,
            handler(newVal) {
                if (!newVal) {
                    this.selectedItems = []
                    return
                }
                
                // 处理外部传入值
                if (this.multiple) {
                    const ids = Array.isArray(newVal) ? newVal : [newVal]
                    this.selectedItems = this.products.filter(p => ids.includes(p.id))
                } else {
                    const id = Array.isArray(newVal) ? newVal[0] : newVal
                    this.selectedItems = this.products.filter(p => p.id === id)
                }
            }
        }
    },
    mounted() {
        this.recentItems = JSON.parse(localStorage.getItem('recentProducts')) || []
    },
    methods: {
        async showDialog() {
            this.dialogVisible = true
            try {
                await this.$nextTick()
                // 默认选中"全部"节点
                this.$refs.categoryTree.setCurrentKey(0)
                this.handleCategoryClick({ id: 0 }) // 触发加载根分类
            } catch (error) {
                console.error('初始化失败:', error)
                this.$message.error('分类加载失败，请稍后重试')
            }
        },

        async loadRootCategories() {
            try {
                const res = await this.$axios.get(`/Waste/Type/List?pid=0&dataPERType=${this.dataPERType}`)
                console.log('根分类数据:', res) // 添加日志输出
                return res.filter(item => item.usestate === '已启用')
            } catch (error) {
                console.error('加载根分类失败:', error)
                return []
            }
        },

        async loadCategories(node, resolve) {
            try {
                let data = [];
                if (node.level === 0) {
                    data = [
                        {
                            id: 0,
                            name: '全部',
                            isLeaf: false,
                        }
                    ]
                    resolve(data)
                } else if(node.level === 1){
                    data = await this.loadRootCategories();
                } else {
                    const res = await this.$axios.get(`/Waste/Type/List?pid=${node.data.id}&dataPERType=${this.dataPERType}`);
                    data = res;
                }
                
                // 添加节点转换逻辑
                const processedData = data.map(item => ({
                    ...item,
                    isLeaf: item.isLeaf || false // 根据实际数据结构调整
                }));
                
                resolve(processedData.filter(item => item.usestate === '已启用'));
            } catch (error) {
                console.error('加载分类失败:', error);
                resolve([]);
            }
        },

        async handleCategoryClick(data) {
            try {
                const res = await this.$axios.get(`/Waste/product/List?typeId=${data.id}&dataPERType=${this.dataPERType}`)
                this.products = res.filter(item => item.usestate === '已启用')
            } catch (error) {
                console.error('加载可回收物失败:', error)
                this.$message.error('可回收物加载失败')
            }
        },

        handleSelect(item) {
            this.selectedItem = item
            this.dialogVisible = false
            this.updateRecentItems(item)

            this.$emit('input', item.id)
            this.$emit('select', {
                id: item.id,
                name: item.name,
                price: item.price
            })
        },

        updateRecentItems(item) {
            this.recentItems = [
                item,
                ...this.recentItems.filter(i => i.id !== item.id)
            ].slice(0, 10) // 修改为10条
            this.saveToLocalStorage()
        },

        // 新增方法：删除单个
        removeRecentItem(item) {
            this.recentItems = this.recentItems.filter(i => i.id !== item.id)
            this.saveToLocalStorage()
            this.$message.success('已删除该历史记录')
        },

        // 新增方法：清空全部
        clearAllRecent() {
            this.recentItems = []
            this.saveToLocalStorage()
            this.$message.success('已清空所有历史记录')
        },

        // 公共保存方法
        saveToLocalStorage() {
            localStorage.setItem('recentProducts', JSON.stringify(this.recentItems))
        },

        // 统一处理点击
        handleItemClick(item) {
            if (this.multiple) {
                this.toggleSelection(item)
            } else {
                this.selectSingle(item)
            }
        },

        // 单选处理
        selectSingle(item) {
            this.selectedItems = [item]
            this.dialogVisible = false
            this.updateRecentItems(item)
            this.emitChange()
        },

        // 多选处理
        toggleSelection(item) {
            const index = this.selectedItems.findIndex(i => i.id === item.id)
            if (index > -1) {
                this.selectedItems.splice(index, 1)
            } else {
                this.selectedItems.push(item)
            }
            console.log('多选处理-this.selectedItems:',this.selectedItems)
            this.updateRecentItems(item)
            this.emitChange()
        },

        // 判断选中状态
        isSelected(item) {
            return this.selectedItems.some(i => i.id === item.id)
        },

        // 删除单个选中
        removeSelected(item) {
            this.selectedItems = this.selectedItems.filter(i => i.id !== item.id)
            this.emitChange()
        },

        // 统一数据传递
        emitChange() {
            const output = this.multiple 
                ? this.selectedItems.map(i => i.id) 
                : this.selectedItems[0]?.id || null
            this.$emit('input', output)
            this.$emit('select', this.multiple ? this.selectedItems : this.selectedItems[0])
        },

        //清除选中值
        clearSelection(){
            console.log('清除选中值')
            this.selectedItems = [{
                id: null,
                name: '请选择',
            }]
            this.emitChange()
        },

        // 确认选择（多选时）
        confirmSelect(){
            this.$emit('confirmSelect',this.selectedItems)
            this.dialogVisible = false
        }
    }
}
</script>

<style lang="scss" scoped>
// 在全局或组件样式添加
@mixin text-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.product-selector {
    .trigger-box {
        cursor: pointer;
        height: 40px;

        .el-input__inner {
            display: flex;
            padding-right: 5px
        }

        .selected-content {
            display: flex;
            flex: 1;
            align-items: center;
            gap: 8px;
        }

        .placeholder {
            color: #606266;
            flex: 1;
        }

        .el-input__icon{
            color: #C0C4CC;
        }

        &.mini{
            .el-input__inner{
                height: 32px;
                line-height: 32px;
                font-size: 13px;
            }
            .el-input__icon{
                line-height: 32px;
            }
        }
    }
}

.dialog-content {
    padding: 10px;

    .search-input {
        margin-bottom: 15px;
    }

    .section-title {
        font-weight: 500;
        margin: 10px 0;
        color: #606266;
        margin-top: 0;
    }
}

.category-tree {
    border-right: 1px solid #ebeef5;
    padding-right: 15px;
    height: 400px;
    overflow: auto;

    .tree-node {
        font-size: 14px;

        i {
            margin-right: 6px;
            color: #909399;
        }
    }
}

.product-list {
    height: 400px;
    overflow: auto;
    padding-left: 15px;

    .product-items {
        display: grid;
        grid-template-columns: repeat(4, 1fr); // 三列布局
        gap: 12px; // 项目间距

        .product-item {
            padding: 12px;
            margin: 0; // 去除原margin
            border: 1px solid #ebeef5;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            flex-direction: column;
            text-align: center;
            line-height: 3em;
            // min-height: 60px; // 统一高度

            &:hover {
                transform: translateY(-3px);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            .name {
                font-weight: 500;
                color: #303133;
                // margin-bottom: 6px;
                @include text-ellipsis; // 添加文字截断
                width: 100px;
                font-size: 16px;
            }

            .price {
                color: #409eff;
                font-size: 13px;
                margin: auto 0 4px 0; // 自动撑开
            }

            .remark {
                color: #909399;
                font-size: 12px;
                @include text-ellipsis; // 添加文字截断
                width: 100px;
                margin-top: 6px;
            }
        }
    }
}

.recent-section {
    margin-bottom: 15px;

    .recent-items {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }

    .recent-tag {
        cursor: pointer;
        transition: transform 0.2s;

        &:hover {
            transform: scale(1.05);
        }
    }
}
// 多选样式
.multi-selected {
    border-color: #67C23A!important;
    background-color: #f0f9eb!important;
    
    .selected-icon {
        color: #67C23A!important;
    }
}

// 单选样式
.selected {
    border-color: #409EFF!important;
    background-color: #ecf5ff!important;
    
    .selected-icon {
        color: #409EFF!important;
    }
}

.selected-content {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
    align-items: center;
}

:deep(.el-tree-node__content) {
    height: 36px;
}
</style>